/**
 * Created by Admin on 30.12.2014.
 */

var LoadingQueue = (function ($) {

    return $.inherit({
        options: {
            onComplete: $.noop
        },

        tasks: null,

        __constructor: function (tasks, options) {
            this.options = $.extend({}, this.options, options);
            this.tasks = tasks
        },

        load: function (onComplete) {
            var tasks = this.tasks;
            var extendedResults = {};
            var results = {};
            var total = Object.keys(tasks).length;
            var succeed = 0;
            var failed = 0;
            var finished = 0;

            function tryFinalize() {
                finished++;
                finished == total && (onComplete && onComplete(extendedResults, results, {
                    total: finished,
                    succeed: succeed,
                    failed: failed
                }));
            }

            function tryFinalizeFailure() {
                failed++;
                tryFinalize();
            }

            $.each(tasks, function (taskName, task) {
                try {
                    task.execute(function (result) {
                        extendedResults[taskName] = {
                            result: result,
                            metaData: task.metaData
                        };
                        results[taskName] = result
                        succeed++;
                        tryFinalize();
                    }, function () {
                        tryFinalizeFailure();
                    });
                } catch (e) {
                    tryFinalizeFailure();
                }
            });
        }

    })

})(window["jQuery"]);